package com.ailot.cloud.auth.config;



import com.ailot.cloud.auth.handler.JwtAuthenticationFailureHandler;
import com.ailot.cloud.auth.handler.JwtAuthenticationSuccessHandler;
import com.ailot.cloud.base.security.handler.JwtLogoutSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.web.SecurityFilterChain;

/**
 * @author 认证相关配置
 */
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfigurer {


    private final JwtEncoder jwtEncoder;

    public WebSecurityConfigurer(JwtEncoder jwtEncoder) {
        this.jwtEncoder = jwtEncoder;
    }

    @Bean("loginFilterChain")
    public SecurityFilterChain loginFilterChain(HttpSecurity http) throws Exception {
        return
                http
                        .requestMatchers().antMatchers("/login", "/logout")
                        .and()
                        .cors(cors -> cors.disable())
                        .csrf(csrf -> csrf.disable())
                        .formLogin()
                        .successHandler(new JwtAuthenticationSuccessHandler(jwtEncoder))
                        .failureHandler(new JwtAuthenticationFailureHandler())
                        .and()
                        .logout(logout -> logout.logoutSuccessHandler(new JwtLogoutSuccessHandler()))
                        .build();
    }

}
